package com.xia.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xia.pojo.Admin;
import com.xia.pojo.Category;
import com.xia.pojo.Reader;
import com.xia.service.AdminService;
import com.xia.service.CategoryService;
import com.xia.service.ReaderService;
import com.xia.utils.AjaxUtils;
import com.xia.utils.Const;
import com.xia.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class CommonController {

    @Autowired
    public AdminService adminService;

    @Autowired
    public ReaderService readerService;

    @Autowired
    public CategoryService categoryService;

    /**
     *  跳转到登录页面
     * @return 登录页面
     */
    @RequestMapping("/toLogin")
    public String toLogin() {
        return "login";
    }

    /**
     *  跳转到注册页面
     * @return 注册页面
     */
    @RequestMapping("/toRegister")
    public String toRegister() {
        return "register";
    }

    /**
     *  退出登录
     * @param session session
     * @return 登录页面
     */
    @RequestMapping("/logout")
    public String logOut(HttpSession session) {
        // 清除session，跳转到登录页面
        session.invalidate();
        return "login";
    }

    /**
     *  登录成功跳转main
     * @param session session
     * @return main页面
     */
    @RequestMapping("/toMain")
    private String toMain(HttpSession session) {
        List<Category> categoryList = categoryService.listCategory();
        session.setAttribute(Const.CATEGORY, categoryList);
        return "main";
    }

    @RequestMapping("/toReaderMain")
    public String toReaderMain(HttpSession session) {
        List<Category> categoryList = categoryService.listCategory();
        session.setAttribute(Const.CATEGORY, categoryList);
        return "readerMain";
    }

    /**
     *  登录
     * @param name 用户名/学号
     * @param password 密码
     * @param access 权限
     * @param session session
     * @return 结果集
     */
    @PostMapping("/realLogin")
    @ResponseBody
    public String realLogin(String name, String password, String access, HttpSession session) {

        AjaxUtils ajaxResult = new AjaxUtils();
        Map<String, Object> map = new HashMap<>();
        map.put("name", name);
        map.put("password", password);
        try {
            if (access.equals("0")) {
                Admin realAdmin = adminService.adminQuery(map);
                if (realAdmin != null) {
                    ajaxResult.setCode(0);
                    ajaxResult.setStatus("0");
                    ajaxResult.setMessage("管理员账户" + name + "登录成功！");
                    ajaxResult.setSuccess(true);
                    session.setAttribute(Const.ADMIN, realAdmin);
                } else {
                    ajaxResult.setCode(-1);
                    ajaxResult.setStatus("-1");
                    ajaxResult.setMessage("管理员账户" + name + "不存在！");
                    ajaxResult.setSuccess(true);
                }
            } else if (access.equals("1")) {
                Reader reader = readerService.readerLoginQuery(map);
                if (reader != null) {
                    ajaxResult.setStatus("1");
                    ajaxResult.setCode(1);
                    ajaxResult.setMessage("读者" + name + "登录成功！");
                    ajaxResult.setSuccess(true);
                    session.setAttribute(Const.READER, reader);
                } else {
                    ajaxResult.setCode(-1);
                    ajaxResult.setStatus("-1");
                    ajaxResult.setMessage("读者账户" + name + "不存在！");
                    ajaxResult.setSuccess(true);
                }
            } else {
                ajaxResult.setSuccess(false);
                ajaxResult.setCode(2);
                ajaxResult.setStatus("2");
                ajaxResult.setMessage("登录出现异常，请检查权限！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajaxResult.setCode(3);
            ajaxResult.setStatus("3");
            ajaxResult.setMessage("服务器异常！");
            ajaxResult.setSuccess(false);
        }

        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.writeValueAsString(ajaxResult);
        } catch (Exception e) {
            e.printStackTrace();
            return "{\"code\": -1, \"msg\": \"JSON处理错误\"}";
        }
    }

    /**
     *  注册页检查学号是否可用
     * @param readerId 学号
     * @return 结果集
     */
    @PostMapping("/checkReader")
    @ResponseBody
    public String checkReader(Integer readerId) {

        AjaxUtils ajaxUtils = new AjaxUtils();
        Integer count = readerService.readerQueryByReaderId(readerId);
        if (count == 0) {
            // 未查到，表示学号可用
            ajaxUtils.setCode(0);
            ajaxUtils.setSuccess(true);
            ajaxUtils.setStatus("0");
            ajaxUtils.setMessage("可用");
        } else {
            ajaxUtils.setCode(-1);
            ajaxUtils.setStatus("-1");
            ajaxUtils.setSuccess(false);
            ajaxUtils.setMessage("当前学号/借阅号已被注册！");
        }

        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.writeValueAsString(ajaxUtils);
        } catch (Exception e) {
            e.printStackTrace();
            return "{\"code\": -1, \"msg\": \"JSON处理错误\"}";
        }
    }

    /**
     *  新用户注册（新用户初始默认可借10本书籍）
     * @param reader 新用户
     * @return 结果
     */
    @PostMapping("/readerRegister")
    @ResponseBody
    public String readerRegister(Reader reader) {

        AjaxUtils ajaxUtils = new AjaxUtils();
        try {
            readerService.readerRegister(reader);
            ajaxUtils.setCode(1);
            ajaxUtils.setSuccess(true);
            ajaxUtils.setMessage("注册成功！");
            ajaxUtils.setStatus("1");
        } catch (Exception e) {
            e.printStackTrace();
            ajaxUtils.setCode(-1);
            ajaxUtils.setSuccess(false);
            ajaxUtils.setMessage("注册失败！");
            ajaxUtils.setStatus("-1");
        }

        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.writeValueAsString(ajaxUtils);
        } catch (Exception e) {
            e.printStackTrace();
            return "{\"code\": -1, \"msg\": \"JSON处理错误\"}";
        }
    }

    @RequestMapping("/updatePwd")
    public String updatePwd(String state, Model model) {
        model.addAttribute("state", state);
        return "alterPwd";
    }

    @RequestMapping("/checkPwd")
    @ResponseBody
    public String checkPassword(String state, String password, HttpSession session, Model model) {

        model.addAttribute("state", state);

        AjaxUtils ajaxUtils = new AjaxUtils();
        Integer count = 0;
        try {
            if (StringUtil.isEmpty(password)) {
                ajaxUtils.setSuccess(false);
                ajaxUtils.setCode(-1);
                ajaxUtils.setStatus("-1");
                ajaxUtils.setMessage("旧密码不能为空");
            }
            // 0
            if (state.equals("0") && StringUtil.isNotEmpty(password)) {
                Admin admin = (Admin) session.getAttribute(Const.ADMIN);
                count = adminService.checkPwd(admin);
            }
            // 1
            if (state.equals("1") && StringUtil.isNotEmpty(password)) {
                Reader reader = (Reader) session.getAttribute(Const.READER);
                count = readerService.checkPwd(reader);
            }
            if (count == 1) {
                ajaxUtils.setSuccess(true);
                ajaxUtils.setCode(0);
                ajaxUtils.setStatus("0");
                ajaxUtils.setMessage("旧密码正确");
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajaxUtils.setSuccess(false);
            ajaxUtils.setCode(-1);
            ajaxUtils.setStatus("-1");
            ajaxUtils.setMessage("旧密码错误");
        }

        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.writeValueAsString(ajaxUtils);
        } catch (Exception e) {
            e.printStackTrace();
            return "{\"code\": -1, \"msg\": \"JSON处理错误\"}";
        }
    }

    /**
     *  修改密码（暂时存在问题：密码可以修改成功，但页面未关闭未跳转）
     * @param state 权限
     * @param password 密码
     * @param session session
     * @return 结果
     */
    @RequestMapping("/editPwd")
    @ResponseBody
    public String editPassword(String state, String password, HttpSession session) {
        AjaxUtils ajaxUtils = new AjaxUtils();
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("password", password);
        try {
            // 0:管理员修改密码
            if (state.equals("0")) {
                Admin admin = (Admin) session.getAttribute(Const.ADMIN);
                paramMap.put("id", admin.getId());
                adminService.editPwd(paramMap);
            }
            // 1:读者修改密码
            if (state.equals("1")) {
                Reader reader = (Reader) session.getAttribute(Const.READER);
                paramMap.put("id", reader.getId());
                paramMap.put("readerId", reader.getReaderId());
                readerService.editPwd(paramMap);
            }
            ajaxUtils.setSuccess(true);
            ajaxUtils.setCode(0);
            ajaxUtils.setStatus("0");
            ajaxUtils.setMessage("更新成功！");
        } catch (Exception e) {
            e.printStackTrace();
            ajaxUtils.setSuccess(false);
            ajaxUtils.setCode(-1);
            ajaxUtils.setStatus("-1");
            ajaxUtils.setMessage("更新失败！");
        }

        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.writeValueAsString(ajaxUtils);
        } catch (Exception e) {
            e.printStackTrace();
            return "{\"code\": -1, \"msg\": \"JSON处理错误\"}";
        }
    }
}